﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebApplicationRating.DB.model;
using System.Configuration;
using System.Web.Configuration;

namespace WebApplicationRating.Views
{
    public partial class ImageUpload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

         protected void valFile_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (!uploadedFile.HasFile)
            {
                args.IsValid = false;
            }
        }

         protected void valFileType_ServerValidate(object source, ServerValidateEventArgs args)
         {
             if (uploadedFile.HasFile)
             {
                 string[] acceptedTypes = new string[] 
        { 
                 
                 "image/jpeg", 
                 "image/tiff",
                 "image/bmp",
                 "image/gif", 
                 "image/png" 
        };

                    if (!acceptedTypes.Contains(uploadedFile.PostedFile.ContentType))
                     {
                         args.IsValid = false;
                     }
                    
             
             }

             
         
         }


        public void FileUploadButton_Click(object sender, EventArgs e)
        {
            string path = Server.MapPath("images/") + uploadedFile.PostedFile.FileName;  
            if (IsValid)
            {
                //string path = Server.MapPath("images/") + uploadedFile.PostedFile.FileName;

                uploadedFile.SaveAs(path);
                Image1.ImageUrl = "images/" + uploadedFile.PostedFile.FileName;
            }
         



            //Valid images
           // if (uploadedFile.PostedFile != null &&
           //     uploadedFile.PostedFile.FileName != "")

            if (IsValid)
                                  
            {

                //  uploadedFile.SaveAs(path);

                //  Image1.ImageUrl = "images/" + uploadedFile.PostedFile.FileName; 
                //TODO check to see if it already exists...
                using (imageEntities ctx = new imageEntities())
                {
                    WebApplicationRating.DB.model.Image newImage = new WebApplicationRating.DB.model.Image();
                    //populate the image_file field
                    byte[] imageBinaryData = new byte[uploadedFile.PostedFile.ContentLength];
                    HttpPostedFile uploadedImage = uploadedFile.PostedFile;
                    uploadedImage.InputStream.Read(imageBinaryData, 0, (int)uploadedFile.PostedFile.ContentLength);
                    newImage.image_file = imageBinaryData;

                    //populate the filename field, override the default uploaded filename if user has entered name
                    string strImageName = uploadedFile.PostedFile.FileName;
                    string strUploadComment = uploadComment.Text.ToString();
                    if (imageName.Text != null &&
                        imageName.Text != "") 
                    
                    strImageName = imageName.Text.ToString();
                    newImage.name = strImageName;
                    newImage.user_upload_comment = strUploadComment;
                    
                    
                    //populate the source_url field
                    newImage.source_url = strImageName;

                    //populate the upload_date field
                    newImage.upload_date = DateTime.Now;
                    ctx.AddToImages(newImage);
                 

                    //now build and save the corresponding UserImage entry
                    UserImage curUserImage = new UserImage();
                    curUserImage.imageid = newImage.imageid;
                    //TODO - HARDCODED!!! the user_image.userid field needs to be dynamically assigned
                    //string userName = WebConfigurationManager.AppSettings["PFUserName"].ToString();

                    //int curUserId = Convert.ToInt32(WebConfigurationManager.AppSettings["UserID"].ToString());
                    int curUserId = SharedItems.Field2;
                    curUserImage.userid = curUserId;
                    curUserImage.favorite = "N";

                    ctx.AddToUserImages(curUserImage);

                    //now build and save the corresponding ImageCategory entry(s)
                    //if not were selected by user on upload, default to 'Other'
                    int categoriesSelected = 0;
                    for (int i = 0; i < categoryCheckBoxList.Items.Count; i++)
                    {
                        if (categoryCheckBoxList.Items[i].Selected)
                        {
                            categoriesSelected++;
                            ImageCategory curImageCategory = new ImageCategory();
                            curImageCategory.imageid = newImage.imageid;
                            curImageCategory.categoryid = Convert.ToInt32(categoryCheckBoxList.Items[i].Value.ToString());
                            ctx.AddToImageCategories(curImageCategory);
                        }
                    }
                    //if none selected store at least 1 default value
                    if (categoriesSelected == 0)
                    {
                       for (int i = 0; i < categoryCheckBoxList.Items.Count; i++)
                       {
                           if (categoryCheckBoxList.Items[i].Text.ToString() == WebConfigurationManager.AppSettings["DefaultImageCategory"].ToString())
                           {
                               categoriesSelected++;
                               ImageCategory curImageCategory = new ImageCategory();
                               curImageCategory.imageid = newImage.imageid;
                               curImageCategory.categoryid = Convert.ToInt32(categoryCheckBoxList.Items[i].Value.ToString());
                               ctx.AddToImageCategories(curImageCategory);
                           }
                       }
                    }

                    //account for the possibility that the DefaultImageCategory was accidentally deleted!
                    if (categoriesSelected == 0)
                    {
                        lblMessage.Text = "No Category Assigned!  Default category must have been deleted from db.  Please contact system administrators!";
                    }
                    else
                    {
                        int result = ctx.SaveChanges();
                        if (result > 0)
                        {
                            lblMessage.Text = "Image Saved!";
                            imageName.Text = "";
                            uploadComment.Text = "";


                            
                            for (int i = 0; i < categoryCheckBoxList.Items.Count; i++)
                            {
                                if (categoryCheckBoxList.Items[i].Selected)
                                {
                                    categoryCheckBoxList.Items[i].Selected = false;

                                }
                            }


                        }
                        else
                            lblMessage.Text = "Error Saving Image!";
                    }
                    
                    
                   
                }
            }




                
            }

                     
        }

    }

